package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dao.GoodsTopMapper;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.entity.GoodsTop;
import com.eco.fanliapp.service.FindItemIdUtils;
import com.eco.fanliapp.service.HDKUtils;
import com.eco.fanliapp.service.IGoodsTopService;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo.NTbkItem;
import com.eco.fanliapp.vo.TbkPrivilegeGetInfo.TbkPrivilege;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

@Service
public class GoodsTopServiceImpl extends ServiceImpl<GoodsTopMapper, GoodsTop> implements IGoodsTopService {

//    private static final Logger log = LoggerFactory.getLogger(GoodsTopServiceImpl.class);

    @Autowired
    private GoodsTopMapper goodsTopMapper ;

    @Autowired
    private AppGoodsMapper appGoodsMapper ;
//    @Autowired
//    private ITaoBaoService iTaoBaoService;
//    @Autowired
//    private ITaoBaoMethodService iTaoBaoMethodService;
    @Autowired
    private FindItemIdUtils taoBaoUtils;


    /**
     * 增加置顶商品
     * 根据商品id
     * @param goodsTop
     * @return
     */
    @Override
    public ServerResponse addGoodsTop(GoodsTop goodsTop) {
        //默认总公司
        goodsTop.setCompanyId(1);
        //默认淘宝
        goodsTop.setGoodsPlatform(1);
        if(!RegUtils.isNumeric(goodsTop.getGoodsId())){
            return ServerResponse.createByErrorMessage("商品id格式不正确");
        }
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("goodsId",goodsTop.getGoodsId());
//        hashMap.put("companyId",goodsTop.getCompanyId());
        int size = goodsTopMapper.findAll(hashMap).size();
        if(size > 0){
            return ServerResponse.createByErrorMessage("该商品已存在");
        }
    	//查询当前商品ID是否在商品库
    	AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(goodsTop.getGoodsId());
    	if(appGoods != null) {
            //goodsTop.setGoodsPlatform(goodsTop.getGoodsPlatform());
    		goodsTop.setGoodsName(goodsTop.getGoodsName() == null ? appGoods.getItemshorttitle(): goodsTop.getGoodsName());
			goodsTop.setGoodsPictureUrl(appGoods.getItempic());
	        goodsTop.setGoodsTitle(appGoods.getItemtitle());
	        goodsTop.setGoodsDecription(appGoods.getItemshorttitle());
	        goodsTop.setGoodsTopStage(1);
	        int i = goodsTopMapper.insertSelective(goodsTop);
	        if( i > 0) {
	        	return ServerResponse.createBySuccess("数据获取成功", appGoods);
	        }else {
	        	return ServerResponse.createByErrorMessage("商品添加失败");
	        }
    	}else {
    		//如果不存在查好单库
    		HaoDanKuItemInfo info = taoBaoUtils.getHaoDanKuItemId(goodsTop.getGoodsId());
			if(info != null && info.getCode() == 1 && info.getData() != null){
				//goodsTop.setGoodsPlatform(goodsTop.getGoodsPlatform());
				goodsTop.setGoodsName(goodsTop.getGoodsName() == null ? info.getData().getItemshorttitle(): goodsTop.getGoodsName());
				goodsTop.setGoodsPictureUrl(info.getData().getItempic());
    	        goodsTop.setGoodsTitle(info.getData().getItemtitle());
    	        goodsTop.setGoodsDecription(info.getData().getItemtitle());
    	        goodsTop.setGoodsTopStage(1);
    	        int i = goodsTopMapper.insertSelective(goodsTop);
    	        if(i > 0) {
    	        	AppGoods goods = HDKUtils.getAppGoodsFromHDK(info.getData());
    	        	//goods.setCompanyId(goodsTop.getCompanyId());

                    goods.setCreateTime(DateUtils.getNowTimestamp());
                    goods.setUpdateTime(DateUtils.getNowTimestamp());
                    goods.setRecommend(1);
    	        	int i2 = appGoodsMapper.insertAppGoods(goods);
    	        	if(i2 > 0) {
    	        		return ServerResponse.createBySuccessMessage("商品添加成功");
    	        	}else {
    	        		return ServerResponse.createByErrorMessage("商品添加失败");
    	        	}
    	        }else {
    	        	return ServerResponse.createByErrorMessage("商品添加失败");
    	        }
    		}else {
    			//查询淘宝详情
    			List<NTbkItem> items = taoBaoUtils.getTaoBaoItemId(goodsTop.getGoodsId());
    			if(items != null && items.size() > 0) {
    				for (NTbkItem nTbkItem : items) {
    					//goodsTop.setGoodsPlatform(goodsTop.getGoodsPlatform());
    					goodsTop.setGoodsName(goodsTop.getGoodsName() == null ? nTbkItem.getTitle(): goodsTop.getGoodsName());
    					goodsTop.setGoodsPictureUrl(nTbkItem.getPictUrl());
    	    	        goodsTop.setGoodsTitle(nTbkItem.getTitle());
    	    	        goodsTop.setGoodsDecription(nTbkItem.getTitle());
    	    	        goodsTop.setGoodsTopStage(1);
    	    	        int i = goodsTopMapper.insertSelective(goodsTop);
    	    	        if(i > 0) {
    	    	        	AppGoods goods2 = HDKUtils.getAppGoodsFromTB(nTbkItem);
    	    	        	TbkPrivilege privilege = taoBaoUtils.getPrivilegeItemId(Long.valueOf(goods2.getItemid() == null ? "0" : goods2.getItemid()));
                            goods2.setCouponmoney(Double.valueOf(privilege.getCouponInfo() == null ? "0" : privilege.getCouponInfo()));
    	    	        	goods2.setCouponstarttime(privilege.getCouponStartTime() == null?"0": DateFormatUtils.dateToStamp(privilege.getCouponStartTime()).toString());
    	    	        	goods2.setCouponendtime(privilege.getCouponEndTime() == null?"0": DateFormatUtils.dateToStamp(privilege.getCouponEndTime()).toString());
    	    	        	goods2.setEndTime(privilege.getCouponEndTime() == null?"0": DateFormatUtils.dateToStamp(privilege.getCouponEndTime()).toString());
                            BigDecimal itemendprice = BigDecimalUtils.Format(
                                    new BigDecimal(nTbkItem.getZkFinalPrice() == null ? "0" : nTbkItem.getZkFinalPrice())
                                            .subtract(new BigDecimal(privilege.getCouponInfo()))
                            );
    	    	        	goods2.setItemendprice(itemendprice.doubleValue());
    	    	        	goods2.setTkrates(privilege.getMaxCommissionRate());
    	    	        	goods2.setItemprice(nTbkItem.getZkFinalPrice().toString());
//    	    	        	goods2.setTkmoney(BigDecimalUtils.FanliMoney(privilege.getMaxCommissionRate(),
//    	    	        			BigDecimalUtils.Format(
//    	    	    	        			Double.valueOf(nTbkItem.getZkFinalPrice() == null ? "0" : nTbkItem.getZkFinalPrice())
//    	    	    	        			-
//    	    	    	        			Double.valueOf(privilege.getCouponInfo() == null ? "0" : privilege.getCouponInfo()))).toString());
                            String tkMoney = Double.valueOf(
                                    BigDecimalUtils.FanliMoney(privilege.getMaxCommissionRate(),
                                            itemendprice).doubleValue()).toString();
                            goods2.setTkmoney(tkMoney);
                            //goods2.setCompanyId(goodsTop.getCompanyId());

                            goods2.setCreateTime(DateUtils.getNowTimestamp());
                            goods2.setUpdateTime(DateUtils.getNowTimestamp());
                            goods2.setRecommend(1);
    	    	        	int i2 = appGoodsMapper.insertAppGoods(goods2);
    	    	        	if(i2 > 0) {
    	    	        		return ServerResponse.createBySuccessMessage("商品添加成功");
    	    	        	}else {
    	    	        		return ServerResponse.createByErrorMessage("商品添加失败");
    	    	        	}
    	    	        }else {
    	    	        	return ServerResponse.createByErrorMessage("商品添加失败");
    	    	        }
					}
    			}
    			return ServerResponse.createByErrorMessage("商品不存在");
    		}
    	}

    }


    @Override
    public GoodsTop selectByGoodsId(String goodsId) {
        return goodsTopMapper.selectByGoodsId(goodsId);
    }





    /**
     * 查询所有免单商品
     * @return
     */
    @Override
    public ServerResponse<PageInfo> findAll(Integer companyId, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage,pageSize);
        HashMap<String,Object> hashMap = new HashMap<>();hashMap.put("companyId",companyId);
        List goodsTops = goodsTopMapper.findAll(hashMap);
        if(goodsTops == null){
            ServerResponse.createByErrorMessage("查询失败");
        }
        return ServerResponse.createBySuccess("查询成功",new PageInfo(goodsTops));
    }

    /**
     * 根据平台查询免单商品
     * @param platform
     * @return
     */
    @Override
    public ServerResponse<List> selectByPlatform(Integer platform) {
        List<GoodsTop> goodsFreeList = goodsTopMapper.selectByGoodsPlatform(platform);
        return ServerResponse.createBySuccess("数据查询成功",goodsFreeList);
    }

    /**
     *  根据商品Id删除数据库的记录,goods_free
     *
     * @param goodsId
     */
    @Override
    public ServerResponse deleteByGoodsId(String goodsId) {

        int deleteNum = goodsTopMapper.deleteByGoodsId(goodsId);
        if(deleteNum == 1){
        	appGoodsMapper.deleteByGoodsId(Long.valueOf(goodsId));
            return ServerResponse.createBySuccessMessage("数据删除成功");
        }

        return ServerResponse.createByErrorMessage("数据删除不成功");
    }

    /**
     *  动态字段,根据商品Id来更新符合条件的数据库记录,goods_free
     *
     * @param record
     */
    @Override
    public ServerResponse<List> updateByPrimaryKeySelective(GoodsTop record) {
        int updateNum = goodsTopMapper.updateByGoodsIdSelective(record);
        List list = goodsTopMapper.findAll(null);
        return ServerResponse.createBySuccess("数据修改成功",list);
    }

    @Override
    public ServerResponse<List> selectByGoodsIdOrGoodsName(String goodsIdOrGoodsName) {

        List<GoodsTop> goodsFreeList = goodsTopMapper.selectByGoodsIdOrGoodsName(goodsIdOrGoodsName);

        return ServerResponse.createBySuccess("数据查询成功",goodsFreeList);
    }
    /**
     * 根据平台或关键字查询置顶商品
     * @param goodsPlatform
     * @param keyWord
     * @return
     */
    @Override
    public ServerResponse<PageInfo> selectGoodsTopByKeyWord(Integer companyId, Integer goodsPlatform, String keyWord , Integer currentPage, Integer pageSize) {

        PageHelper.startPage(currentPage,pageSize);

       // PageInfo pageInfo = new PageInfo();
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("companyId",companyId);
        hashMap.put("goodsPlatform",goodsPlatform);
        hashMap.put("keyWord",keyWord);
        List goodsFrees = goodsTopMapper.findAll(hashMap);

        if (goodsFrees == null ){
            return ServerResponse.createByErrorMessage("查询失败");
        }
            return ServerResponse.createBySuccess("查询成功",new PageInfo(goodsFrees));



    }
    /**
     * 根据商品 id 修改商品置顶状态
     * @param goodsId
     * @return
     */
    @Override
//    @Transactional
    public ServerResponse updateGoodsTopStageByGoodsId(String goodsId, Integer goodsTopStage) {
       /* GoodsTop goodsTop = goodsTopMapper.selectByGoodsId(goodsId);
        Integer topStage = goodsTop.getGoodsTopStage();*/
        GoodsTop goodsTop = goodsTopMapper.selectByGoodsId(goodsId);
        int stageNum = appGoodsMapper.updateGoodsTopAndtopSerialNumber(goodsId, goodsTopStage, goodsTop.getTopSerialNumber());
        if (stageNum <= 0)return ServerResponse.createByErrorMessage("修改置顶状态不成功，商品库没有该商品") ;
        int updateNum = goodsTopMapper.updateGoodsTopStageByGoodsId(goodsId,goodsTopStage);
        if (updateNum == 1) return ServerResponse.createBySuccessMessage("修改置顶状态成功");
        return ServerResponse.createByErrorMessage("修改置顶状态不成功") ;
    }

    /**
     * 根据商品id批量修改商品置顶状态
     * @param goodsIds
     * @return
     */
    @Override
    public ServerResponse updateGoodsTopStageByGoodsIds(String[] goodsIds, Integer goodsTopStage){

        boolean flag = false ;
        for (String goodsId : goodsIds) {
            GoodsTop goodsTop = goodsTopMapper.selectByGoodsId(goodsId);
            Integer topStage = goodsTop.getGoodsTopStage();
            // 判断数据库中的商品是否置顶
            if (topStage == 2){
                return ServerResponse.createBySuccessMessage("选中商品中拥有已置顶商品");
            }
            int updateNum = goodsTopMapper.updateGoodsTopStageByGoodsId(goodsId,goodsTopStage);
            if (updateNum == 1){
                int stageNum = appGoodsMapper.updateGoodsTopStageByGoodsId(goodsId, goodsTopStage);
                if (stageNum == 1){
                    flag = true ;
                    continue;
                }
                return ServerResponse.createByErrorMessage("修改置顶状态不成功") ;
            }
            return ServerResponse.createByErrorMessage("修改置顶状态不成功") ;
        }
        if (flag){
            return ServerResponse.createByErrorMessage("修改置顶状态成功") ;
        }
        return ServerResponse.createByErrorMessage("修改置顶状态不成功") ;
    }

    /**
     * 批量删除商品
     * @param goodsIds
     * @return
     */
    @Override
    public ServerResponse deleteByGoodsIds(String[] goodsIds) {


        for (String goodsId : goodsIds) {
            int deleteNum = goodsTopMapper.deleteByGoodsId(goodsId);
            if (deleteNum == 1) {
                continue;
            }

            return ServerResponse.createByErrorMessage("数据删除不成功");
        }

        return ServerResponse.createByErrorMessage("数据删除成功");
    }

    @Override
    public ServerResponse updateSerial(HashMap<String, Object> hashMap) {
        MapValueHelper mapValueHelper = new MapValueHelper(hashMap);
        int topSerialNumber = mapValueHelper.getInt("topSerialNumber");
        int id = mapValueHelper.getInt("id");
        int size = goodsTopMapper.findTopSerialMax(topSerialNumber,id).size();
        if(size > 0){
            return ServerResponse.createByErrorMessage("序号重复，请重新输入");
        }else {
            GoodsTop goodsTop = goodsTopMapper.selectByPrimaryKey(id);
            int i = goodsTopMapper.updateSerial(hashMap);
            hashMap.put("itemid",goodsTop.getGoodsId());
            if (goodsTop.getGoodsTopStage() == 1 && i > 0) {
                return ServerResponse.createBySuccess();
            } else if (goodsTop.getGoodsTopStage() == 2 && i > 0){
                int appUserTopNum = appGoodsMapper.updateGoodTopNum(hashMap);
                if (appUserTopNum > 0) {
                    return ServerResponse.createBySuccess();
                }
            }

            return ServerResponse.createByErrorMessage("修改失败");
        }
    }

    @Override
    public int insertSelective(GoodsTop goodsTop) {
        return goodsTopMapper.insertSelective(goodsTop);
    }

    @Override
    public int deleteByGoodsIdReturnInt(String itemid) {
        return  goodsTopMapper.deleteByGoodsId(itemid);
    }
}
